import axios from 'axios'
import { message, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import store from "@/store";
import { resetUser } from "@/store/action";
import { useDispatch } from 'react-redux';

const { confirm } = Modal

const baseURL = 'http://localhost:3000'
const version = '/api/react'

// 创建axios实例
const service = axios.create({
    baseURL: baseURL + version,
    timeout: 500
})

// 添加请求拦截器
service.interceptors.request.use(
    config => {
        // 添加token
        config.headers.Authorization = localStorage.getItem('token')
        return config
    },
    error => {
        console.log(error); // for debug
        return Promise.reject(error)
    }
)

// 添加响应拦截器
service.interceptors.response.use(
    response => {
        // 代码走到这里，http状态码=200
        const res = response.data
        if (res.err !== 0) {
            message.error(res.msg || '入参有误')
            // 篡改token、token过期、token伪造
            if (res.err === -1) {
                // 重新登录
                confirm({
                    title: '当前登录已失效',
                    icon: <ExclamationCircleOutlined />,
                    content: '请重新登录',
                    okText: '重新登录',
                    // 隐藏取消按钮，要求必须重新登录
                    cancelButtonProps: {
                        style: {
                            display: 'none'
                        }
                    },
                    // onFinish() {
                    //     store.dispatch(resetUser())
                    // }
                    onOK() {
                        store.dispatch(resetUser())
                    }
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res.data
        }
    },
    error => {
        console.log('err' + error);
        return Promise.reject(error)
    }
)

export default service